<template>
  <div class="pc-upload-container">
    <!-- 返回按钮和标题 -->
    <div class="header">
      <el-button :icon="ArrowLeft" @click="onClickLeft" class="back-btn"></el-button>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/category/' }">文物主体管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/category/' }">{{ currentCategory.name }}</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '' }">编辑文物主体</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <div class="loading-text">加载中...</div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <el-empty description="加载失败，请重试" image="error">
        <template #bottom>
          <el-button type="primary" @click="fetchCategoryData">重试</el-button>
        </template>
      </el-empty>
    </div>

    <el-form v-else ref="formRef" label-width="160px" class="upload-form" :model="formData.category" :rules="formRules">
      <!-- 基本信息 -->
      <el-card class="form-card">
        <template #header>文物主体基本信息</template>

        <el-form-item label="名称" prop="name"
          :rules="[{ required: true, message: '请输入名称', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.category.name" placeholder="请输入文物主体名称" />
        </el-form-item>
        <el-form-item label="地理位置" prop="address"
          :rules="[{ required: true, message: '请输入地理位置', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.category.address" type="textarea" :rows="2" placeholder="请输入详细地理位置或存放地址" />
        </el-form-item>
        <el-form-item label="建筑年代" prop="construction_age"
          :rules="[{ required: true, message: '请输入建筑年代', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.category.construction_age" placeholder="例如：建于清康熙中期（公元1700年）（朝代/具体年份）" />
        </el-form-item>

        <!-- 建筑类型 -->
        <el-form-item label="建筑类型" prop="construction_type_selected"
          :rules="[{ required: true, message: '请至少选择一种建筑类型', trigger: ['blur', 'change'] }]">
          <el-checkbox-group v-model="formData.category.construction_type_selected">
            <el-checkbox label="市井戏台">市井戏台</el-checkbox>
            <el-checkbox label="庙宇戏台">庙宇戏台</el-checkbox>
            <el-checkbox label="宗祠戏台">宗祠戏台</el-checkbox>
            <el-checkbox label="其他">其他</el-checkbox>
          </el-checkbox-group>

          <!-- “其他”自定义输入框 -->
          <!-- 使用 div 包裹，强制换行 -->
          <!-- “其他”自定义输入框 -->
          <div v-if="formData.category.construction_type_selected.includes('其他')"
            style="display: block; width: 100%; margin-top: 15px;">
            <el-form-item prop="construction_type_other" :rules="otherRules">
              <el-input v-model="formData.category.construction_type_other" placeholder="请输入其他建筑类型"
                style="width: 300px;" />
            </el-form-item>
          </div>
        </el-form-item>

        <el-form-item label="布局方位" prop="layout_orientation"
          :rules="[{ required: true, message: '请输入布局方位', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.category.layout_orientation" placeholder="例如：坐北朝南、依山而建等" />
        </el-form-item>

        <!-- 保护级别 -->
        <el-form-item label="保护级别" prop="protection_level_main"
          :rules="[{ required: true, message: '请至少选择一种保护级别', trigger: ['blur', 'change'] }]">
          <el-radio-group v-model="formData.category.protection_level_main">
            <el-radio label="国宝单位">国宝单位</el-radio>
            <el-radio label="省级">省级</el-radio>
            <el-radio label="市县级">市县级</el-radio>
            <el-radio label="未定级">未定级</el-radio>
          </el-radio-group>

          <!-- 所有级别都支持补充信息 -->
          <div class="protection-extra-wrapper">
            <el-input v-model="formData.category.protection_level_extra" placeholder="补充信息，如：（批次：第 1 批全国重点文物保护单位）"
              style="width: 450px;" />
          </div>
        </el-form-item>

        <el-form-item label="描述" prop="description"
          :rules="[{ required: true, message: '请输入描述', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.category.description" type="textarea" :rows="4"
            placeholder="请输入该文物主体的历史背景、文化价值等描述" />
        </el-form-item>
      </el-card>

      <!-- 类别图片 -->
      <el-card class="form-card">
        <template #header>主体图片</template>

        <el-form-item label="主图">
          <div class="image-upload-container">
            <!-- 预览区域 -->
            <div v-if="currentCategory.image && !imageChanged.value" class="image-preview">
              <el-image :src="currentCategory.image_base64" fit="cover" class="preview-image" />
            </div>

            <!-- 上传区域 -->
            <el-upload v-model:file-list="formData.category.image" list-type="picture-card"
              :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-change="handleImageChange"
              :auto-upload="false" :limit="1">
              <!-- 自定义触发按钮内容 -->
              <template #default>
                <div style="display:flex;flex-direction:column;align-items:center;">
                  <el-icon style="font-size:18px;color:#909399;margin-bottom:4px;">
                    <Plus />
                  </el-icon>
                  <div style="font-size:12px;color:#c0c4cc;text-align:center;">上传新图可替换</div>
                </div>
              </template>
            </el-upload>


            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </div>
        </el-form-item>

      </el-card>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          保存修改
        </el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { useCategoryEdit } from '@/components/composables/useCategoryEdit'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { computed } from 'vue'

const {
  formData,
  loading,
  error,
  submitLoading,
  formRef,
  dialogImageUrl,
  dialogVisible,
  formRules,
  currentCategory,
  imageChanged,
  handlePictureCardPreview,
  handleRemove,
  handleImageChange,
  fetchCategoryData,
  handleSubmit,
  handleCancel,
  onClickLeft,
} = useCategoryEdit()

// 动态校验规则：只有选了“其他”才必填
const otherRules = computed(() => {
  if (formData.category.construction_type_selected?.includes('其他')) {
    return [
      { required: true, message: '请填写具体的其他建筑类型', trigger: 'blur' }
    ]
  }
  return [] // 不选“其他”时，无需校验
})
</script>

<style scoped>
/* 复用上传页面样式，并补充编辑页面特有样式 */
.pc-upload-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
}

.back-btn {
  margin-right: 15px;
}

.title {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.upload-form {
  max-width: 900px;
  margin: 0 auto;
}

.form-card {
  margin-bottom: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.el-card__header {
  background-color: #f5f7fa;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  margin-bottom: 50px;
}

/* 图片上传区域样式 */
.image-upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.image-preview {
  width: 200px;
  height: 200px;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 20px;
}

.loading-text {
  margin-top: 20px;
  font-size: 16px;
  color: #666;
}

.error-state {
  padding: 40px 20px;
  text-align: center;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 保护级别补充输入框的容器：强制换行 */
.protection-extra-wrapper {
  display: block;
  margin-top: 15px;
  /* 与上方输入框的间距 */
}

/* 输入框宽度 */
.other-input {
  width: 300px;
}
</style>
